#coding=utf8
import sys, MangaBase, re, urllib2, urlparse
import cmrhelper, decode
from cmrhelper import GbkToUtf8, UtfToGbk
class Parser(MangaBase.CMangaBase):
    "http://dm.99770.com/Comic/ parser"
    def IniRe(self):
        self.namere = re.compile("<meta name=\"keywords\" content=\"(.*?)\">")
        self.chapterre = re.compile(r'<div id=b><img src=/images/i.gif hspace=3><a  class=link01 href=(.*?) target=_blank>(.*?)</a></div>')
        self.pagenumre = re.compile(r'datas=(\d+);')
        self.pagere = re.compile(r'(^http.*)(\?v=)\d(\*s=(\d*\b))')
        self.picre = re.compile(r'var picurl=\"(.*?)\"')
        self.hostre = re.compile(r'(ServerList\[\d*\]=.*?;)')


    def ParseName(self):
        "get manga name if name is None"
        self.m_mangalog.writeLog('get manga name')
        if self.namere.findall(self.chaptercontent):
            self.m_manganame = GbkToUtf8(self.namere.findall(self.chaptercontent)[0])
            self.m_mangalog.writeLog('get manga name success, manga name [%s]' %\
                                         self.m_manganame)

    def ParseChapter(self, curl, title):
        "parse each chapter to generate url of pictures"
        pagelist = []
        piclist = []
        content = ''
        try:
            self.GetServerlist(curl)
            content = urllib2.urlopen(curl).read()
            if content:
                pagelist = self.GetPageurls(curl,content)
            for item in pagelist:
                picurl = self.ParsePic(item)
                self.PushPic([picurl, picurl, title, self.m_manganame])
            return piclist
        except  Exception, e:
            self.m_mangalog.writeLog(str(e))

    def GetChapters(self):
        "get manga chapters"
        try:
            if self.chapterre.findall(self.chaptercontent):
                for item in self.chapterre.findall(self.chaptercontent):
                    self.m_chapterlist.append([GbkToUtf8(urlparse.urljoin(self.m_url, item[0])),\
                                                   GbkToUtf8(item[1])])
                    self.m_chaptercnt += 1
            self.m_mangalog.writeLog('get chapters finish total: [%d] chapters'\
                                         % self.m_chaptercnt)
        except  Exception, e:
            self.m_mangalog.writeLog(str(e)+' in getchapter','error')

    def GetServerlist(self, url):
        self.ServerList = ServerList = ['']*20
        ServerList[0]="http://110.99770.com:8333/";
        url = urlparse.urljoin(url,'/haodm/dmJS/love.js')
        content = urllib2.urlopen(url).read()
        l = self.hostre.findall(content)
        if l:
            for item in l:
                exec(item)
            return True
        else:
            return False

    def GetPageurls(self, url, content):
        "get each url of pages"
        '''urlformat: http://dm.99770.com/Comic/1274/12066/?v=1*s=4'''
        self.HostID = 0
        
        pagelist = []
        if self.pagenumre.findall(content)[0].isdigit():
            pagelist.append(url)
            pagenum = int(self.pagenumre.findall(content)[0])
            if self.pagere.findall(url):
                urlpre = self.pagere.findall(url)[0][0]
                urlmid = self.pagere.findall(url)[0][1]
                urltail = self.pagere.findall(url)[0][2]
                self.HostID = int(self.pagere.findall(url)[0][3])
                self.m_mangalog.writeLog('hostid: ' + str(self.HostID))
                for i in range(2,pagenum):
                    pagelist.append(urlpre + str(i) + '.htm' + urlmid + str(i) + urltail)
            return pagelist
        else:
            return None

    def ParsePic(self, url):
        content = urllib2.urlopen(url).read()
        if content:
            if self.picre.findall(content):
                return urlparse.urljoin(self.ServerList[self.HostID-1], \
                                            self.picre.findall(content)[0])
        else:
            return None

